package org.dei.perla.sys.hlqexecutor;

import org.dei.perla.component.Startable;
import org.dei.perla.parser.util.Duration;


/**
 * @author  luigi
 */
public class ViewTimeBased extends View implements Startable {

/**
 * @uml.property  name="interval"
 * @uml.associationEnd  
 */
private Duration interval;
private Thread viewThread;

public ViewTimeBased(Query qSQL, Duration interval){
	super(qSQL);
	this.interval = interval;
	this.viewThread = new Thread(new ThreadImplementation());
}
	


@Override
public boolean isStarted() {
	return this.viewThread.isAlive();
}

@Override
public void start() {
	this.viewThread.start();
	
}

@Override
public void stop() {
	if(isStarted()){
		this.viewThread.interrupt();
	}
	
}

private class ThreadImplementation extends Thread {
	long timeInMillis;
	public ThreadImplementation() {
		//fare attenzione che la conversioni non super il valore di un long
		switch (interval.getTimeUnit()){
			case MILLISECONDS: timeInMillis = (long) interval.getValue();
				break;
			case SECONDS: timeInMillis = (long) interval.getValue() * 1000;
				break;
			case MINUTES: timeInMillis = (long) interval.getValue() * 60 * 1000;
				break;
			case HOURS: timeInMillis = (long) interval.getValue() * 60 * 60 * 1000;
				break;
			case DAYS: timeInMillis = (long) interval.getValue() * 24 * 60 * 60 * 1000;
				break;
			case MONTHS: timeInMillis = (long) interval.getValue() * 30  * 24 * 60 * 60 * 1000;
				break;
		}
		
		
	}
	
	@Override
	public void run(){
		try{
			while(!viewThread.isInterrupted()){
				//TODO aggiorna la vista sql creata ad intervalli di tempo regolari (tempi dettati dall'oggetto interval)
				Thread.sleep(timeInMillis);
			}
		}catch (InterruptedException e){
			e.printStackTrace();
		}
	}
}

}
